<?php

namespace Index\Controller;

use Think\Controller;

class CommonController extends Controller {

    protected $_id = 0;
    protected $_Info = array();
    protected $_needLogin = false;
    protected $_pageTitle = '八九六中文_八九六小说网';
    protected $_pageKeywords = '八九六中文,八九六中文网,八九六小说网';
    protected $_pageDescription = '八九六中文致力于打造无弹窗的在线小说网站，收录了当前最热门、最火爆的小说，提供小说在线阅读，小说TXT下载，网站没有弹窗广告页面简洁';

    protected $offset = 0;
    protected $limit = 18;
    protected $page = 1;


    /**
     *
     * @var type
     */
    protected $_url = '';
    private $_getfilter = "'|<[^>]*?>|^\\+\/v(8|9)|\\b(and|or)\\b.+?(>|<|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $_postfilter = "^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    public function __construct() {
        parent::__construct();
        if(isMobileBrow() && MODULE_NAME != 'Wap'){
            header('Location: '.C('WAP_SITE'));
            //$this->redirect(C('WAP_SITE'));
            exit();
        }

        $page = I('request.page');
        $this->page = empty($page)?1:$page;
        C('TOKEN_ON',false);
    }

    public function _initialize(){
        $this->_id = session('_id');
        if ($this->_needLogin){
            if (empty($this->_id)) {
                session_destroy();
                $this->redirect('/'.MODULE_NAME.'/login',null,0,'');exit();
            }
            session('_info',\Common\Library\COM\MemberDo::getLoginInfo($this->_id));
            $this->_Info = session('_info');
        }
    }


    /**
     * 图片上传处理
     * @return type
     */
    public function UploadImg(array $config){
        $configs = array(
            'rootPath' => I('server.DOCUMENT_ROOT').'/Public/Uploads', //保存根路径
            'maxSize' => empty($config['maxSize'])?0:$config['maxSize'],
            'savePath' => empty($config['savePath'])?'/default':$config['savePath'],
            //'saveName' => empty($config['saveName'])?'':$config['saveName'],
            'exts' => empty($config['exts'])?array('jpg', 'gif', 'png', 'jpeg'):$config['exts'],
            'autoSub' => empty($config['autoSub'])?false:$config['autoSub'], //开启子目录保存
            'subName' => empty($config['subName'])?'getSubName':$config['subName'],
            );
        $upload = new \Think\Upload($configs); // 实例化上传类
        $info = $upload->upload();
        // 采用时间戳命名
        $upload->saveName = 'time';
        if (!$info) {// 上传错误提示错误信息
            \Think\Log::write('sssssss ttttt Error :' . var_export($_FILES, 1));
            \Think\Log::write('Upload Files Error :' . var_export($upload->getError(), 1));
            return array('status' => 'error', 'msg' => $upload->getError());
        }else {// 上传成功
            $targetFile = '/Public/Uploads'.$info['image']['savepath'].$info['image']['savename'];
            $image_id = md5(time().getRandStr());
            $imgs = array('image_id' => $image_id,'storage' => 'file','url' => $targetFile,'last_modified' => time()
            );
            D('Common/Image')->SaveData($imgs);
            return array('status' => 200, 'msg' => $targetFile,'image_id'=>$image_id);
        }
    }



    /**
     *
     * 发站内信
     * @param mixed $member_id
     * @param string $message 发送内容
     */
    protected function SendMsg($member_id, $message) {
        if (empty($member_id) && empty($message)) {
            return FALSE;
        }

        return Common::SysMsg($member_id, $message);
    }

    /**
     * 邮件群发
     *
     * @param mixed $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    protected function SendMail($mailto, $subject, $body) {
        //return false;
        if (is_string($mailto)) {
            $mailto = explode(',', $mailto);
        }
        foreach ($mailto as $mail) {
            $this->MailTo($mail, $subject, $body);
        }
    }

    /**
     * 发送邮件
     * @param string $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    private function MailTo($mailto, $subject, $body) {
        //Thinkphp的导入方式，放在/ThinkPHP/Extend/Vendor/
        //vendor('PHPMailer.class#phpmailer');
        import("Common.Library.Vendor.PHPMailer.class", '', '.phpmailer.php');
        //创建mail对象
        $mail = new PHPMailer();
        $mail->IsSMTP(); //设置使用SMTP服务器发送
        $mail->Host = "smtp.exmail.qq.com";  //设置发件箱的服务器
        $mail->SMTPAuth = true;     // 设置需要验证
        $mail->Username = "regist@uli9.com";  // 发件人使用邮箱
        $mail->Password = 'ww.360.cn'; // 设置发件人密码
        $mail->From = "regist@uli9.com"; // 发件人邮箱
        $mail->FromName = C('SYS_NAME'); //发送者名称
        $mail->AddAddress($mailto); // 添加发送地址
        $mail->IsHTML(true); //指定支持html格式
        $mail->CharSet = "UTF-8";
        $mail->Subject = $subject;
        $mail->Body = $body;
        //dump($mail->Send());exit();
        if ($mail->Send()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送手机短信
     *
     * @param string $number
     * @param string $message
     * @return boolean
     */
    protected function SendSMS($number, $message) {
        if (is_string($number)) {
            $number = explode(',', $number);
        }
        foreach ($number as $val) {
            $this->SMS($val, $message);
        }
    }

    /**
     * 发送手机短信
     *
     * @param string $number
     * @param string $message
     * @return boolean
     */
    private function SMS($number, $message) {
        if (!\Validate::IsCellphone($number) && empty($message)) {
            return FALSE;
        }
        $url = 'http://120.25.202.19:8888/sms.aspx';
        //'http://106.ihuyi.cn/webservice/sms.php?method=Submit';
        $postData = 'action=send&extno=&userid=' . C('SMS_ID') . '&account=' . C('SMS_USER') . '&password=' . C('SMS_PASS');
        $postData .= '&mobile=' . $number . '&content=' . rawurlencode($message);
        //短信发送初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $return_str = curl_exec($curl);
        curl_close($curl);
        //\Think\Log::write("send message:".var_export($return_str,1));
        preg_match("/<code>(\d+)<\/code>/", $return_str, $pre_arr_num);
        //\Think\Log::write("send message:".var_export($return_str))
        if ($pre_arr_num[1] == '2') {
            return true;
        } else {
            return false;
        } //0提交失败,2提交成功,408同一手机号码一分钟之内发送频率超过10条，系统将冻结你的帐号
    }




    //校验验证码
    protected function checkVerify($code) {
        $verify = new \Think\Verify();
        return $verify->check($code);
    }
    //获取验证码图片
    public function getVerify(){
        $length = empty($_GET['l'])?6:$_GET['l'];
        $imageH = empty($_GET['h'])?40:$_GET['h'];
        $imageW = empty($_GET['w'])?233:$_GET['w'];
        $fontSize = empty($_GET['s'])?20:$_GET['s'];
        $useNoise = empty($_GET['u'])?true:false;
        $config = array(
            'fontSize' => $fontSize, // 验证码字体大小
            'length' => $length, // 验证码位数
            'useNoise' => $useNoise, // 关闭验证码杂点
            'imageH'=> $imageH,
            'imageW'=> $imageW,
        );
        $Verify = new \Think\Verify($config);
        $Verify->entry();
    }

    //分页数据处理方法
    public function showPage($count){
        $p = I('get.p');
        $this->page = empty($p)?1:$p;
        $Page       = new \Think\Page($count,$this->limit);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $Page->rollPage   = 10;// 分页栏每页显示的页数
        $Page->setConfig('header','<span id="pagestats">%NOW_PAGE%/%TOTAL_ROW%</span>');

        $Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');

        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        //$Page->firstRow.','.$Page->listRows
        $this->offset = ($this->page - 1) * $this->limit;


        //p($show);exit;
        $this->assign('showPage',$show);// 赋值分页输出
    }

    public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {

        $this->assign('pageTitle',$this->_pageTitle);
        $this->assign('pageDescription',  $this->_pageDescription);
        $this->assign('pageKeywords',  $this->_pageKeywords);
        $this->assign('memberId',  $this->_id);
        $this->assign('memberInfo',  $this->_Info);
        $this->assign('page',$this->page);

        $Link = new \Common\Model\LinkModel();
        $this->assign('links',$Link->getList('','`weight` desc'));
        $this->assign('navs',\Common\Model\BookCateModel::getNavigation());

        parent::display($templateFile,$charset,$contentType,$content,$prefix);
    }


    public function layerIfreamRe($msg='',$url = '',$type='success'){
        if($type == 'error'){
            $msg = empty($msg)?'操作失败':$msg;
        }else{
            $msg = empty($msg)?'操作成功':$msg;
        }
        if(empty($url)){
            $dourl = 'location.href=history.go("-1")';
        }else{
            $dourl = 'location.href="'.$url.'"';
        }
        echo <<<Eof
        <script src="/Public/plugin/gb312/js/jquery.min.js" ></script>
        <script src="/Public/plugin/gb312/js/plugins/layer/layer.min.js" ></script>
        <script src="/Public/plugin/gb312/js/plugins/sweetalert/sweetalert.min.js"></script>
        <link href="/Public/plugin/gb312/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
        <script>
            $(function(){
                 swal({
                    title:"{$msg}",
                    text:"",
                    type:"{$type}",
                },function(){
                    //当你在iframe页面关闭自身时
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);
                    {$dourl};
                });
            });
        </script>
Eof;
            exit;
    }

    public function _empty(){
        $this->error('页面不存在');
    }
}
